import type { BaseResponse } from '../models/up_response.ts';
import { SerialPortFactory } from '../models/factories/SerialPortFactory';
import apiClient from '../utils/axiosInterceptors';

export class SerialInfoService {
  /** 通用 POST 并校验返回状态 */
  private static async postAndCheck<T>(url: string, data?: any): Promise<T> {
    const response = await apiClient.post<BaseResponse<T>>(url, data);
    if (response.data.status) {
      return response.data.data as T;
    }
    throw SerialPortFactory.createSerialError(
      response.data.message || 'Unknown error'
    );
  }

  static getMode(serial_id: string, protocol_id: number): Promise<boolean> {
    return this.postAndCheck<boolean>(
      '/serial/mode',
      SerialPortFactory.createHttpRequest(serial_id, protocol_id)
    ).then((data) => data ?? false);
  }

  static loadInfoStart(
    serial_id: string,
    protocol_id: number
  ): Promise<boolean> {
    // 这里返回 status，data 为 null
    return apiClient
      .post<BaseResponse<null>>(
        '/serial/load_info/start',
        SerialPortFactory.createLoadInfoRequest(serial_id, protocol_id, 1)
      )
      .then((response) => {
        if (response.data.status) {
          return true;
        }
        throw SerialPortFactory.createSerialError(
          response.data.message || 'Unknown error'
        );
      });
  }

  static loadInfoStop(
    serial_id: string,
    protocol_id: number
  ): Promise<boolean> {
    return this.postAndCheck<null>(
      '/serial/load_info/stop',
      SerialPortFactory.createHttpRequest(serial_id, protocol_id)
    ).then(() => true);
  }

  static loadInfoStopForId(serial_id: string): Promise<boolean> {
    return this.postAndCheck<null>(
      '/serial/load_info/stop/serial',
      SerialPortFactory.createHttpRequest(serial_id, 0)
    ).then(() => true);
  }

  static loadInfoStopAll(): Promise<boolean> {
    return this.postAndCheck<null>('/serial/load_info/stop/all').then(
      () => true
    );
  }
}
